#include "h264_framed_live_source.hpp"
#include <opencv2/opencv.hpp>
#include <thread>
#include <mutex>
#include <memory>
#include <atomic>
#include <mutex>
#include <functional>
#include "h264_encode.hpp"


H264FramedLiveSource*  H264FramedLiveSource::createNew(UsageEnvironment& env,VideoDevice* device)
{
    H264FramedLiveSource* new_source = new H264FramedLiveSource(env,device);
    return new_source;
}

H264FramedLiveSource::H264FramedLiveSource(UsageEnvironment& env,VideoDevice* device): FramedSource(env)
                                                                 , have_start_reading(false)
                                                                 , video_device_(device)
{
    //此处添加自己的初始化代码
}

H264FramedLiveSource::~H264FramedLiveSource ()
{
    //此处添加自己的析构代码
    
}

unsigned H264FramedLiveSource::maxFrameSize()const
{
    //此处添加最大的帧长度,需要根据编码器去调整，如果无法确定最大值，则设置为0
    LOG(INFO)<<"Get max size:"<<1280*720*3;
    return 1280*720*3;
}
void H264FramedLiveSource::doGetNextFrame()
{
    /**
     * @brief 此处给出的是如何从内存中读取h264编码数据并放入到live555的缓冲区中.
     * 
     * 首先需要调用memcpy(fTo,xx,size), 要确保数据不丢之，必须保证fMaxSize 大于等于最大的h264帧长度
     * 拷贝完成后，设置fFrameSize变量为读取的字节数,下面给出一个示例:
     * fFrameSize = XXXgetH264Frame(fTo, fMaxSize);
     * if(fFrameSize ==0 )
     * {
     *    handleClourse();
     *    return;
     * }
     * 
     * 读取完成后需要设置时间戳
     * gettimeofday(&fPresentationTime,NULL);
     * 最后通知调用者
     * nextTask()=envir().taskScheduler().scheduleDelayedTask(0, (TaskFunc*)FramedSource::afterGetting,this);
     */
    size_t h264_buffer_size = fMaxSize;
    LOG(INFO)<<"h264 max buffer size:"<<fMaxSize;
    video_device_->get_h264_buffer(fTo,&h264_buffer_size);
    LOG(INFO)<<" get encoder size:"<<h264_buffer_size;
    fFrameSize = h264_buffer_size;
    gettimeofday(&fPresentationTime,NULL);
    nextTask()=envir().taskScheduler().scheduleDelayedTask(0, (TaskFunc*)FramedSource::afterGetting,this);
}